<template>
  <Card>
    <p slot="title">
      批量代付
    </p>
    <div class="record">
      <Row type="flex" justify="start" class="code-row-bg">
        <record-list v-for="(item,index) in recordData" :key="index" :item="item">
        </record-list>
      </Row>
    </div>
    <div style="height: 20px;"></div>
    <i-form ref="form" :model="formInline" :rules="ruleInline" :label-width="95">
      <Form-item prop="password" label="支付密码">
        <i-input type="password" v-model="formInline.password" placeholder="请输入密码" number></i-input>
      </Form-item>

      <Form-item label="上传文件" prop="url">
        <Upload action=""
        accept=".xls, .xlsx"
        ref="upload"
        :max-size="2048"
        :before-upload="handleBeforUpload"
        :on-success="handleSuccess"
        :on-error ="handleError"
        :on-exceeded-size="handleMaxSize"
        :show-upload-list="false">
          <Button type="info" @click="handleUploadFile">选择文件</Button>
        </Upload>
         <!-- 显示选择的文件名 -->
         <div v-if="file !== null">已选择文件：{{file.name}}
          <Button @click="upload">点击上传</Button><!-- 手动点击上传 -->
         </div>
      </Form-item>

      <div class="texts">系统会核对代付金额，笔数与上传文件是否一致</div>
      <div class="all-news">
        总提交数：<span class="red-color">1 </span> 条，总金额：<span class="red-color">1000</span> 元
      </div>

      <Form-item>
        <i-button class="apply-btn com-btm" @click="submitApply">提交申请</i-button>
        <i-button @click="download" class="demo-btn">
          下载模板
        </i-button>
      </Form-item>
    </i-form>
  </Card>
</template>

<script>
import OSS from 'ali-oss'
import excel from '@/libs/excel'
import RecordList from '@/components/record-list/record-list.vue'
const Money = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('必须项不能为空'))
  }
  // 模拟异步验证效果
  setTimeout(() => {
    callback()
  })
}
export default {
  name: 'batch-upload',
  components: {
    RecordList
  },
  data () {
    return {
      formInline: {
        password: '',
        url: ''
      },
      ruleInline: {
        password: [{
          validator: Money,
          trigger: 'blur'
        }
        ]
      },
      recordData: [{
        title: '可结算金额：',
        num: this.$store.state.user.userInfo.settlable_money,
        color: '#FD2424',
        unit: '元'
      }],
      uploadLoading: false,
      progressPercent: 0,
      showProgress: false,
      showRemoveFile: false,
      // file: '', //选择上传时的文件
      file: null,
      tableData: [],
      tableTitle: [],
      actionPath: 'https://daifuexecl.oss-cn-chengdu.aliyuncs.com'
    }
  },
  methods: {

    initUpload () {
      this.file = null
      this.showProgress = false
      this.loadingProgress = 0
      this.tableData = []
      this.tableTitle = []
    },
    handleUploadFile () {
      console.log(this.tableData)
      this.initUpload()
    },

    // 上传之前
    handleBeforUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.readFile(file)
        this.file = file    // 将回调的文件信息存入data.file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false     // 返回false，表示手动上传，取消默认的自动上传
    },

    // 点击上传按钮触发上传操作
    upload(){
        // sdk提供的创建客户端实例方法
      const client = new OSS({
          region: 'oss-cn-chengdu',
          endpoint: 'oss-cn-chengdu.aliyuncs.com',
          accessKeyId: 'LTAI4GDsCPEp4nUoan4GydPq',
          accessKeySecret: 'bLVGoDCjz60XJSRamr5Sm5isg7pwAE',
          secure:true,
          bucket: 'daifuexecl'
        })

      const Name = this.file.name
      const suffix = Name.substr(Name.indexOf('.'))              // 文件后缀
      // const filename = Date.parse(new Date()) + suffix           // 组成新文件名

      client.multipartUpload(Name, this.file).then(res => {   // 上传
          console.log('上传成功：',res)
          this.$Notice.success({
            title: '提示',
            desc: '上传成功'
          });
          // ... 你的操作，可以拼接图片url，用于显示等...
      }).catch(err => {
          console.log('上传失败：', err)
      })
    },

    //上传成功回调
    handleSuccess (response, file, fileList) {
      console.log(this.file.name)
    },
    //上传失败回调
    handleError (error, file, fileList) {
      this.$Message.error(err.msg)
    },
    //文件超出指定大小限制时的钩子
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '文件已超出指定大小！',
        desc: '文件' + file.name + ' 太大了，不能超过2M.'
      })
    },

    // 读取文件
    readFile (file) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = e => {
        this.uploadLoading = true
        this.tableLoading = true
        this.showProgress = true
      }
      reader.onprogress = e => {
        this.progressPercent = Math.round(e.loaded / e.total * 100)
      }
      reader.onerror = e => {
        this.$Message.error('文件读取出错')
      }
      reader.onload = e => {
        this.$Message.info('文件读取成功')
        const data = e.target.result
        const {
          header,
          results
        } = excel.read(data, 'array')
        const tableTitle = header.map(item => {
          return {
            title: item,
            key: item
          }
        })
        console.log(header)
        this.tableData = results
        this.tableTitle = tableTitle
        this.uploadLoading = false
        this.tableLoading = false
        this.showRemoveFile = true
        this.fileName = file.name
        this.$Message.info('文件上传成功,请提交申请')
        this.handleSuccess(file)
      }
    },
    submitApply() {
      this.$refs.form.validate(valid => {
        if (this.file === null){
          this.$Message.error('您还没有上传文件喔')
          return false
        }
        if (valid) {
          console.log(this.formInline)
          console.log(this.fileName)
          console.log(this.tableData)
          this.$Message.success('Success!')
        } else {
          this.$Message.error('error!')
        }
      })
    },
    download () {
      alert('下载模板')
    }

  }
}
</script>

<style>
  .ivu-card-head {
    position: relative;
  }

  .apply-btn {
    margin-top: 20px;
    margin-left: 100px;
  }

  .upload-btn {
    padding: 10px 20px;
    background-color: #1E9FFF;
    color: #fff;
  }

  .upload-btn:hover {
    background-color: #1E9FFF;
    opacity: .8;
    color: #fff;
  }

  .texts {
    margin: 10px 20px 0px 100px;
    color: red;
  }

  .demo-btn {
    background-color: #FFC633;
    color: #fff;
    margin-top: 20px;
    margin-left: 15px;
  }

  .demo-btn:hover {
    background-color: #FFC633;
    opacity: 0.8;
    color: #fff;
  }

  .ivu-card-head::after {
    content: '';
    position: absolute;
    left: 10px;
    bottom: 0;
    width: 70px;
    border-bottom: 2px solid #5FB878;
  }

  .all-news {
    margin-left: 30px;
    margin-top: 20px;
    font-size: 15px;
  }
</style>
